package com.xoa.service.budget;

import com.xoa.dao.budget.BudgetItemMapper;
import com.xoa.dao.budget.BudgetingProcessMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowRunAttachMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.model.budget.BudgetItem;
import com.xoa.model.budget.BudgetingProcess;
import com.xoa.model.budget.BudgetingProcessFlowRunPrcs;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.WFE.WFERunner.WFEFlowRun;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.rms.impl.RmsFileServiceImpl;
import com.xoa.util.*;
import com.xoa.util.budgetUtil.budgeUtil;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.ipUtil.IpAddr;
import com.xoa.util.netdisk.ZipUtils;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class BudgetingProcessService {
    @Autowired
    private BudgetingProcessMapper budgetingProcessMapper;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private FlowRunPrcsMapper flowRunPrcsMapper;
    @Autowired
    private FlowRunMapper flowRunMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private WFEFlowRunInfo wfeFlowRunInfo;
    @Autowired
    private AttachmentMapper attachmentMapper;
    @Autowired
    private RmsFileServiceImpl rmsFileService;
    @Autowired
    private BudgetItemMapper budgetItemMapper;
    @Autowired
    protected WFEFlowRun wfeFlowRun;
    @Autowired
    private WFELog wfeLog;
    @Autowired
    protected BudgetEnclosureService budgetEnclosureService;
    @Autowired
    protected FlowRunAttachMapper flowRunAttachMapper;


    /**
     * 创建作者:   zxy
     * 创建日期:   2018-05-21
     * 方法介绍:   查询预算执行申请
     */
    public ToJson<BudgetingProcessFlowRunPrcs> queryAllBudgetingProcess(Integer page, Integer pageSize,
                                                                        Boolean useFlag, HttpServletRequest request, String FlowAllow) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        objectMap.put("page", pageParams);
        objectMap.put("userId", users.getUserId());
        objectMap.put("flowAllow", FlowAllow);
        ToJson<BudgetingProcessFlowRunPrcs> json = new ToJson<BudgetingProcessFlowRunPrcs>(1, "error");
        try {
            //查询全部流程
            List<BudgetingProcessFlowRunPrcs> budgetingProcessList = budgetingProcessMapper.queryAllBudgetingProcess(objectMap);
            for (BudgetingProcess budgetingProcess : budgetingProcessList) {
                if (!StringUtils.checkNull(budgetingProcess.getApplicant())) {
                    if (usersMapper.findUsersByuserId(budgetingProcess.getApplicant()) != null) {
                        budgetingProcess.setApplicantName(usersMapper.findUsersByuserId(budgetingProcess.getApplicant()).getUserName());
                    }
                    if (usersMapper.findUsersByuserId(budgetingProcess.getApplicant()) != null) {
                        if (departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(budgetingProcess.getApplicant()).getDeptId()) != null) {
                            budgetingProcess.setDeptId(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(budgetingProcess.getApplicant()).getDeptId()));
                        }
                    }
                }
                if (!StringUtils.checkNull(budgetingProcess.getAllow())) {
                    int allow = Integer.valueOf(budgetingProcess.getAllow());
                    switch (allow) {
                        case 0:
                            budgetingProcess.setAllow("待审批");
                            break;
                        case 1:
                            budgetingProcess.setAllow("已批准");
                            break;
                        case 2:
                            budgetingProcess.setAllow("未批准");
                            break;
                    }
                }
                if (budgetingProcess.getApplicationDate() != null) {
                    budgetingProcess.setApplyDate(DateFormat.getStrDate(budgetingProcess.getApplicationDate()));
                } else {
                    budgetingProcess.setApplyDate("");
                }
                FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.queryByRunId(budgetingProcess.getRunId());
                if (flowRunPrcs != null) {
                    //获取当前步骤id
                    budgetingProcess.setFlowPrcs(flowRunPrcs.getFlowPrcs().toString());
                    //获取当前流程实例id
                    budgetingProcess.setPrcsId(flowRunPrcs.getPrcsId().toString());
                } else {
                    budgetingProcess.setFlowPrcs("");
                    budgetingProcess.setPrcsId("");
                }
                FlowRun flowRun = flowRunMapper.find(budgetingProcess.getRunId());
                if (flowRun != null) {
                    budgetingProcess.setRunId(flowRun.getRunId());
                }
            }
            json.setObj(budgetingProcessList);
            json.setMsg("ok");
            json.setFlag(0);
            json.setTotleNum(pageParams.getTotal());
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("BudgetingProcessService queryAllBudgetingProcess:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   zxy
     * 创建日期:   2018-05-21
     * 方法介绍:   新建一条预算申请（配合流程触发器）
     */

    public BaseWrapper addBudgetingProcess(String createDate, HttpServletRequest request) {
        BaseWrapper baseWrapper = new BaseWrapper();
        BudgetingProcess budgetingProcess = new BudgetingProcess();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        //获取当前模块代码
        List<SysCode> SysCode = sysCodeMapper.getSysCode("SALARYTYPE");
        for (com.xoa.model.common.SysCode sysCode : SysCode) {
            if (sysCode.getCodeName().equals("支票领用")) {
                /*
                 * 新建流程接口
                 * flowId:流程id（对应flow_data_+flowId）
                 * prcsId/flowPrcs:前端拼接url参数，直接默认为1
                 * */
                ToJson<FlowFast> flowFastToJson = wfeFlowRunInfo.workFastAdd(users, Integer.parseInt(sysCode.getCodeNo()), 1, "1", "", request, sqlType, "", null);
                if (flowFastToJson.isFlag()) {
                    FlowFast flowFast = (FlowFast) flowFastToJson.getObject();
                    budgetingProcess.setApplicant(users.getUserId());
                    budgetingProcess.setRegisterIp(IpAddr.getIpAddress(request));
                    budgetingProcess.setApplicationDate(DateFormat.getDate(createDate));
                    budgetingProcess.setRunId(flowFast.getFlowRun().getRunId());
                    budgetingProcess.setTableName("budgeting_process");
                    budgetingProcess.setAllow("0");
                    //通过runId在映射表中先插入一条数据，此后的操作通过触发器判断并进行插入
                    int amount = budgetingProcessMapper.insertSelective(budgetingProcess);
                    if (amount > 0) {
                        //获取流程id与流程名称
                        budgetingProcess.setFlowId(flowFast.getFlowTypeModel().getFlowId().toString());
                        budgetingProcess.setFlowName(flowFast.getFlowTypeModel().getFlowName());
                        baseWrapper.setFlag(true);
                        baseWrapper.setStatus(true);
                        baseWrapper.setData(budgetingProcess);
                        baseWrapper.setMsg("ok");
                    }
                }
            }

        }
        return baseWrapper;

    }


    /**
     * 创建作者:   zxy
     * 创建日期:   2018-05-21
     * 方法介绍:   审批操作
     */
    public BaseWrappers approvalProcess(HttpServletRequest request, String num, Integer page, Integer pageSize,
                                        Boolean useFlag) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("信息过期");
            return wrappers;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);
        map.put("userId", users.getUserId());
        wrappers.setTotal(pageParams.getTotal());
        if ("1".equals(num)) {//待办
            //获取当前流程步骤状态
            List<BudgetingProcessFlowRunPrcs> processFlowRunPrcs = budgetingProcessMapper.approvalProcess(map);
            for (BudgetingProcessFlowRunPrcs budgetingProcessFlowRunPrcs : processFlowRunPrcs) {

                if (usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()) != null) {
                    budgetingProcessFlowRunPrcs.setApplicantName(usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()).getUserName());
                }
                if (usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()) != null) {
                    if (departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()).getDeptId()) != null) {
                        budgetingProcessFlowRunPrcs.setDeptId(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()).getDeptId()));
                    }
                }

                if (budgetingProcessFlowRunPrcs.getApplicationDate() != null) {
                    budgetingProcessFlowRunPrcs.setApplyDate(DateFormat.getStrDate(budgetingProcessFlowRunPrcs.getApplicationDate()));
                } else {
                    budgetingProcessFlowRunPrcs.setApplyDate("");
                }
                budgetingProcessFlowRunPrcs.setTableName("budgeting_process");

            }
            wrappers.setFlag(true);
            wrappers.setDatas(processFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        } else if ("2".equals(num)) {//已办
            List<BudgetingProcessFlowRunPrcs> processFlowRunPrcs = budgetingProcessMapper.haveApprovalProcess(map);
            for (BudgetingProcessFlowRunPrcs budgetingProcessFlowRunPrcs : processFlowRunPrcs) {
                if (usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()) != null) {
                    budgetingProcessFlowRunPrcs.setApplicantName(usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()).getUserName());
                }
                if (usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()) != null) {
                    if (departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()).getDeptId()) != null) {
                        budgetingProcessFlowRunPrcs.setDeptId(departmentMapper.getDeptNameById(usersMapper.findUsersByuserId(budgetingProcessFlowRunPrcs.getApplicant()).getDeptId()));
                    }
                }
                if (budgetingProcessFlowRunPrcs.getApplicationDate() != null) {
                    budgetingProcessFlowRunPrcs.setApplyDate(DateFormat.getStrDate(budgetingProcessFlowRunPrcs.getApplicationDate()));
                } else {
                    budgetingProcessFlowRunPrcs.setApplyDate("");
                }
                budgetingProcessFlowRunPrcs.setTableName("budgeting_process");
            }
            wrappers.setFlag(true);
            wrappers.setDatas(processFlowRunPrcs);
            wrappers.setTotal(pageParams.getTotal());
        }

        return wrappers;
    }

    public BaseWrappers selBudgetAttach(HttpServletRequest request, PageParams pageParams, String budgetItemName, String deptId, String applicant, Date startDate, Date endDate) {
        BaseWrappers<BudgetingProcessFlowRunPrcs> baseWrappers = new BaseWrappers<BudgetingProcessFlowRunPrcs>();
        String loginId = (String) request.getSession().getAttribute(
                "loginDateSouse");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("deptId", deptId);
        map.put("startDate", startDate);
        map.put("endDate", endDate);

        if (!StringUtils.checkNull(applicant))
            map.put("applicants", applicant.split(","));
        if (!StringUtils.checkNull(budgetItemName))
            map.put("budgetItemNames", budgetItemName.split(","));

        List<BudgetingProcessFlowRunPrcs> budgetingProcessFlowRunPrcs = budgetingProcessMapper.selBudgetAttach(map);
        for (int i = 0, size = budgetingProcessFlowRunPrcs.size(); i < size; i++) {
            BudgetingProcessFlowRunPrcs entity = budgetingProcessFlowRunPrcs.get(i);
            List<Attachment> attachmentList = GetAttachmentListUtil.returnAttachment(entity.getZipAttachmentName(), entity.getZipAttachmentId(), "xoa" + loginId, "workflow");
            if (attachmentList != null && attachmentList.size() > 0) {
                if (!StringUtils.checkNull(entity.getZipAttachmentName()) && !StringUtils.checkNull(entity.getZipAttachmentId()))
                    entity.setZipAttUrl(attachmentList.get(0).getAttUrl());
            }
        }

        baseWrappers.setDatas(budgetingProcessFlowRunPrcs);
        baseWrappers.setFlag(true);

        map.remove("page");
        int i = budgetingProcessMapper.selBudgetAttachCount(map);
        baseWrappers.setTotal(i);

        return baseWrappers;
    }


    public BaseWrappers<Attachment> saveAttach(HttpServletRequest request, HttpServletResponse response, String attachmentId, String attachmentName, String htmlContent, Integer runId) {

        BaseWrappers<Attachment> baseWrappers = new BaseWrappers<Attachment>();

            // 获取库
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            String company = "xoa" + SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId);
            if (SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId) == null) {
                company = "xoa1001";
            }
            // 获取上传路径
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String os = System.getProperty("os.name");
            StringBuilder uploadHead = new StringBuilder();

            if (os.toLowerCase().startsWith("win")) {
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    uploadHead = uploadHead.append(str2 + "/xoa");
                }
                uploadHead.append(uploadPath);
            } else {
                uploadHead = uploadHead.append(rb.getString("upload.linux"));
            }

            // 获取工作流中的附件信息 进行压缩打包
            List<Attachment> attachmentList = GetAttachmentListUtil.returnAttachment(attachmentName, attachmentId, company, "workflow");
            // 要压缩的文件集合
            List<File> files = new ArrayList<File>();
            // 循环添加
            for (int i = 0, length = attachmentList.size(); i < length; i++) {
                Attachment attachment = attachmentList.get(i);
                StringBuilder flowFilePath = uploadHead;
                flowFilePath.append(System.getProperty("file.separator")).append("attach").
                        append(System.getProperty("file.separator")).
                        append(company).append(System.getProperty("file.separator")).
                        append("workflow").append(System.getProperty("file.separator")).append(attachment.getYm());
                files.add(new File(flowFilePath.toString()));
            }

            // 当前年月
            String ym = new SimpleDateFormat("yyMM").format(new Date());

            // 表单文件存储路径
            StringBuilder htmlFilePathBd = uploadHead;
            htmlFilePathBd.append(System.getProperty("file.separator")).append("attach").
                    append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append("workflow").append(System.getProperty("file.separator")).append(ym);

            // 表单文件路径地址
            String htmlFilePath = htmlFilePathBd.toString();
            // 生成表单文件目录
            new File(htmlFilePath).mkdirs();

            // 获得原始文件名
            String fileName = "工作流表单.html";

            int attachID = Math.abs((int) System.currentTimeMillis());
            String newFileName = Integer.toString(attachID) + "." + fileName;
        // 生成文件
        String filePath = htmlFilePath + System.getProperty("file.separator") + newFileName;
        File f = new File(filePath);

        try( FileOutputStream fileOutputStream = new FileOutputStream(filePath);OutputStreamWriter pw = new OutputStreamWriter(fileOutputStream, "UTF-8")) {
            if (!f.exists()) {
                f.createNewFile();
            }
            // 表单内容写入到表单文件中
            pw.write("<html><head><meta charset=\"UTF-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"></head>");
            pw.write(rmsFileService.HTML_STYLE);
            pw.write("<body>");
            pw.write(htmlContent);
            pw.write("</body></html>");
            //获得模块id
            byte mid = 0;
            for (ModuleEnum em : ModuleEnum.values()) {
                if (em.getName().equals("workflow")) {
                    mid = (byte) em.getIndex();
                }
            }

            // 把表单添加到要压缩的集合中
            files.add(f);
            // 生成压缩包地址
            String zipPath = filePath.replace("预算表单.html", "预算附件.zip");

            ZipUtils.zipFiles(files, zipPath);
            // 获取zipFile
            File zipFile = new File(zipPath);
            // 如果文件不存在
            if (!zipFile.exists()) {
                baseWrappers.setFlag(true);
                baseWrappers.setMsg("zip文件不存在");
                return baseWrappers;
            }

            fileName = "预算附件.zip";
            // 保存进数据库
            Attachment attachment = new Attachment();
            attachment.setAttachId(String.valueOf(attachID));
            attachment.setModule(mid);
            attachment.setAttachFile(fileName);
            attachment.setAttachName(fileName);
            attachment.setYm(ym);
            attachment.setAttachSign(new Long(0));
            attachment.setDelFlag((byte) 0);
            attachment.setPosition((byte) 2);
            attachment.setIsImage((byte) 0);
            attachment.setFileSize(String.valueOf(f.length()));
            attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            attachmentMapper.insertSelective(attachment);

            // 更新附件信息
            BudgetingProcess budgetingProcess = new BudgetingProcess();
            budgetingProcess.setZipAttachmentId(attachment.getAid() + "@" + attachment.getYm() + "_" + attachment.getAttachId());
            budgetingProcess.setZipAttachmentName(attachment.getAttachName());
            budgetingProcess.setRunId(runId);
            budgetingProcessMapper.updateAttachmentByRunId(budgetingProcess);
            baseWrappers.setObject(attachment);
            baseWrappers.setFlag(true);
            baseWrappers.setMsg("ok");

        } catch (Exception e) {
            e.printStackTrace();
            baseWrappers.setFlag(false);
            baseWrappers.setMsg("err");
        }
        return baseWrappers;
    }

    /**
     * 预算执行流程
     *
     * @param budgetId
     * @return
     */
    public BaseWrappers selBudgetingProcessByItem(Integer budgetId) {
        BaseWrappers<BudgetingProcessFlowRunPrcs> baseWrappers = new BaseWrappers<BudgetingProcessFlowRunPrcs>();
        if (budgetId != null) {
            List<BudgetingProcessFlowRunPrcs> budgetingProcessFlowRunPrcs = budgetingProcessMapper.selBudgetingProcessByItem(budgetId);

                for (int i = 0, size = budgetingProcessFlowRunPrcs.size(); i < size; i++) {
                    BudgetingProcessFlowRunPrcs b = budgetingProcessFlowRunPrcs.get(i);
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("budgetIds", (b.getBudgetId()+",").split(","));
                    //用项目客户选择的预算项目（所属部门id、开始时间、结束时间、年度）查出预算项目信息
                    List<BudgetItem> budgetItems1 = budgetItemMapper.selStatistics(map);
                    //budgetingProcessFlowRunPrcs.get(i).setIsPayment(budgetItems1.get(0).getIsPayment());
                    StringBuffer stringBuffer = new StringBuffer();
                    if (b.getBudgetItemBegindate() != null && b.getBudgetItemEnddate() != null) {
                        stringBuffer.append(DateFormat.getDatestr(b.getBudgetItemBegindate()) + " 至 ").append(DateFormat.getDatestr(b.getBudgetItemEnddate()));
                        b.setBudgetZhouQi(stringBuffer.toString());
                    }

                    Users user = usersMapper.findUsersByuserId(b.getApplicant());
                     if (null!=user) {
                         b.setApplicant(user.getUserName());
                     }
                    StringBuilder stringBuilder = new StringBuilder();
                    StringBuilder stringBuilder1 = new StringBuilder();

                    List<Users> usersByUserIdsOrder = usersMapper.getUsersByUserIdsOrder(b.getItemManager().split(","));
                    for (int j = 0, size1 = usersByUserIdsOrder.size(); j < size1; j++) {
                        Users users = usersByUserIdsOrder.get(j);
                        stringBuilder.append(users.getUserName() + ",");
                    }
                    List<Users> usersByUserIdsOrder1 = usersMapper.getUsersByUserIdsOrder(b.getItemExecuter().split(","));
                    for (int j = 0, size1 = usersByUserIdsOrder1.size(); j < size1; j++) {
                        Users users = usersByUserIdsOrder1.get(j);
                        stringBuilder1.append(users.getUserName() + ",");
                    }
                    b.setItemManager(stringBuilder.toString());
                    b.setItemExecuter(stringBuilder1.toString());

                    BudgetItem budgetItem = budgetItemMapper.selBudgetItemById(b.getBudgetId());

                    BigDecimal baiFenBi = b.getActualExpenditure().divide(budgetItem.getItemMoney(),2, BigDecimal.ROUND_HALF_EVEN);

                    DecimalFormat df = new DecimalFormat("#.##%");
                    String format = df.format(baiFenBi);
                    b.setBaiFenBi(format);

                    //b.setSetpName(budgeUtil.switchSetpName(b.getRealPrcsId(),b.getStep(),b.getPrFlag()));
                    // 设置状态
                    b.setSetpName(budgeUtil.switchSetpName(b));
                }


                baseWrappers.setDatas(budgetingProcessFlowRunPrcs);
                baseWrappers.setFlag(true);
                baseWrappers.setMsg("ok");




        }
        return baseWrappers;

    }

    //跟工作流公共附件上传一样，加了一个状态值为了区分二小预算表单公共附件上传要前缀的问题，其他一样
    public ToJson<Attachment> workUpload(MultipartFile[] files, String company, String module, String runId, String flowPrcs, HttpServletRequest request, String flag) {
        ToJson<Attachment> json = new ToJson<Attachment>();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

            List<Attachment> list = budgetEnclosureService.upload2(files, company, module,flag);

            FlowRunAttach flowRunAttach = new FlowRunAttach();
            Object[] o= FileUploadUtil.reAttachment(list);
            flowRunAttach.setRunId(Integer.valueOf(runId));
            flowRunAttach.setAttachmentId(o[0].toString());
            if (StringUtils.checkNull(flowPrcs)){
                flowRunAttach.setFlowPrcs(0);
            }else {
                flowRunAttach.setFlowPrcs(Integer.valueOf(flowPrcs));
            }

            Date d=new Date();
            String d1= DateFormat.getStrDate(d);
            flowRunAttach.setUploadTime(d1);
            flowRunAttach.setUploadUser(users.getUserName());
            flowRunAttach.setAttachmentName(o[1].toString());

            flowRunAttachMapper.insertSelective(flowRunAttach);

            FlowRun flowRun = wfeFlowRun.find(Integer.parseInt(runId));
            String attcahmentId = flowRun.getAttachmentId();
            String attachmentName = flowRun.getAttachmentName();
            StringBuffer id = new StringBuffer();
            StringBuffer name = new StringBuffer();
            if (attcahmentId != "" || attachmentName != "") {
                id.append(attcahmentId);
                name.append(attachmentName);
            }

            map.put("runId", runId);
            if(!StringUtils.checkNull(flowRun.getAttachmentId())){
                if(!",".equals(flowRun.getAttachmentId().substring(flowRun.getAttachmentId().length()-1,flowRun.getAttachmentId().length()))){
                    flowRun.setAttachmentId(flowRun.getAttachmentId()+",");
                }
            }
            if(!StringUtils.checkNull(flowRun.getAttachmentName())){
                if(!"*".equals(flowRun.getAttachmentName().substring(flowRun.getAttachmentName().length()-1,flowRun.getAttachmentName().length()))){
                    flowRun.setAttachmentName(flowRun.getAttachmentName()+"*");
                }
            }

            map.put("attachmentId", flowRun.getAttachmentId() + o[0].toString());
            map.put("attachmentName", flowRun.getAttachmentName() + o[1].toString());
            wfeFlowRun.updateAttachment(map);
            json.setObj(list);
            json.setMsg("OK");
            json.setFlag(0);
            /****   lr 工作流使用添加日志 --上传附件 ****/
            FlowRunLog flowRunLog=wfeLog.getFlowRunLogByRequest(request);
            flowRunLog.setType(Constant.TYPE8);
            flowRunLog.setPrcsId(flowRunAttach.getFlowPrcs());
            flowRunLog.setRunId(Integer.parseInt(runId));
            flowRunLog.setAccessory(flowRun.getAttachmentName() + o[1].toString());
            wfeLog.addFlowRunLog(flowRunLog);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;
    }

}